package com.zhengqing.demo.test;

import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BIRADSClassifier {
    public static void main(String[] args) {
        String input = "右乳肿块伴粗大状钙化BI-RADS 1类";
        System.out.println(findMaxBIRADS(input));
    }

    private static String findMaxBIRADS(String text) {
        // 定义类别到优先级的映射
        Map<String, Integer> priorityMap = new HashMap<>(9);
        // 最高优先级
        priorityMap.put("0", 9);
        priorityMap.put("6", 8);
        priorityMap.put("5", 7);
        priorityMap.put("4A", 6);
        priorityMap.put("4B", 5);
        priorityMap.put("4C", 4);
        priorityMap.put("3", 3);
        priorityMap.put("2", 2);
        priorityMap.put("1", 1);
        int leftBreast = 0;
        int rightBreast = 0;

        // 分割文本为单个描述项
        List<String> items = splitBySerialNumber(text);

        // 正则表达式匹配模式
        Pattern pattern = Pattern.compile("(双侧乳腺|左侧乳腺|右侧乳腺|双乳|左乳|右乳)(.*?)(?:BI-RADS\\s*([0-6]|4[a-c]))类", Pattern.CASE_INSENSITIVE);

        for (String item : items) {
            Matcher matcher = pattern.matcher(item);
            while (matcher.find()) {
                String side = matcher.group(1);
                String categoryStr = matcher.group(3).toUpperCase();
                // 默认值为0
                int priority = priorityMap.getOrDefault(categoryStr, 0);

                if ("双乳".equals(side) || "双侧乳腺".equals(side)) {
                    leftBreast = Math.max(leftBreast, priority);
                    rightBreast = Math.max(rightBreast, priority);
                } else if ("左乳".equals(side) || "左侧乳腺".equals(side))  {
                    leftBreast = Math.max(leftBreast, priority);
                } else if ("右乳".equals(side) || "右侧乳腺".equals(side))  {
                    rightBreast = Math.max(rightBreast, priority);
                }
            }
        }

        // 根据优先级确定最终结果
        int maxCategoryPriority = Math.max(leftBreast, rightBreast);
        if (maxCategoryPriority == 0) {
            return "未找到有效分类";
        } else {
            String resultSide = leftBreast == rightBreast ? "双乳" :
                    leftBreast > rightBreast ? "左乳" : "右乳";

            // 将优先级转换回原始类别表示
            for (Map.Entry<String, Integer> entry : priorityMap.entrySet()) {
                if (entry.getValue().equals(maxCategoryPriority)) {
                    return resultSide + (entry.getKey().startsWith("4") ? "4类" : entry.getKey() + "类");
                }
            }
        }
        return "未找到有效分类";
    }

    private static List<String> splitBySerialNumber(String text) {
        List<String> result = new ArrayList<>();
        String[] split = text.split("；");
        Arrays.stream(split).filter(StrUtil::isNotBlank).forEach(result::add);
        return result;
    }
}